﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using XCore.Authorization;
using SaaS.Model.Entity.Auths;
using System.Data;
using SaaS.Core;
using XCore.Dependency;
using SaaS.Cache.Auths;
using XCore.Extensions;
using SaaS.Model.Enums;

namespace Web.System.Services.Auths
{
    public class RoleAppService : SystemApplicationServiceBase, ITransientDependency
    {
        private readonly SystemAuthCacheService _systemAuthCacheService;
        public RoleAppService(SystemAuthCacheService systemAuthCacheService)
        {
            _systemAuthCacheService = systemAuthCacheService;
        }
        /// <summary>
        /// 创建与编辑
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public bool CreateOrEdit(int id, string name)
        {
            SystemRole role = new SystemRole
            {
                Id = id,
                Name = name,
                Permissions = string.Empty
            };
            if (id == 0)
            {
                if (SDC.SystemRoles.Any(c => c.Name == name)) throw new SystemException("已存在角色名", SystemLoggerSource.Role);
                return Repository.Insert(role) && Logger.Log("添加角色信息", SystemLoggerSource.Role);
            }
            else
            {
                if (SDC.SystemRoles.Any(c => c.Id != id && c.Name == name)) throw new SystemException("已存在角色名", SystemLoggerSource.Role);
                return Repository.Update<SystemRole, string>(id, c => c.Name, name) && Logger.Log(role.Id, "修改角色信息", role, SystemLoggerSource.Role);
            }
        }
        /// <summary>
        /// 删除角色
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public bool Delete(int id)
        {
            if (!SDC.SystemRoles.Any(c => c.Id == id)) throw new SystemException(CoreSetting.Error_ID, SystemLoggerSource.Role);
            if (SDC.SystemAdmins.Any(c => c.RoleId == id)) throw new SystemException("角色包含用户，不可删除", SystemLoggerSource.Role);
            return Repository.Delete<SystemRole>(id) && Logger.Log(id, "删除角色", SystemLoggerSource.Role);
        }
        /// <summary>
        /// 授权
        /// </summary>
        /// <param name="id"></param>
        /// <param name="permissions"></param>
        /// <param name="authorizations"></param>
        public bool Authoriza(int id, string[] permissions, params AuthorizationProvider[] authorizations)
        {
            if (!SDC.SystemRoles.Any(c => c.Id == id)) throw new SystemException(CoreSetting.Error_ID, SystemLoggerSource.Role);
            IReadOnlyList<PermissionChildren> permissionChilder = PermissionFinder.GetAllPermission(authorizations);
            foreach (var item in permissions)
                if (!permissionChilder.Any(c => c.Name.Contains(item))) throw new SystemException($"权限名：{item}，未授权", SystemLoggerSource.Role);
            Repository.Update<SystemRole, string>(id, c => c.Permissions, string.Join(",", permissions));
            _systemAuthCacheService.SaveRolePermission(id, permissions);
            return Logger.Log(id, "角色授权", SystemLoggerSource.Role);
        }
        /// <summary>
        /// 获取角色权限（数据库读）
        /// </summary>
        /// <param name="roleId"></param>
        /// <returns></returns>
        public IEnumerable<string> GetPermissions(int roleId)
        {
            return SDC.SystemRoles.Where(c => c.Id == roleId).Select(c => c.Permissions).FirstOrDefault().ToEnumerable<string>();
        }
        /// <summary>
        /// 获取所有角色（数据库读）
        /// </summary>
        /// <returns></returns>
        public IDictionary<int, string> GetDictionary()
        {
            return SDC.SystemRoles.ToDictionary(c => c.Id, c => c.Name);
        }
    }
}
